<template>
  <div class="params-container">
    <el-card>
      <el-alert
        title="注意：只允许为三级分类设置相关参数！"
        type="warning"
        show-icon
        center
      >
      </el-alert>
      <el-header>
        <strong>请选择商品分类：</strong>
        <el-cascader
          style="display: inline-block"
          :options="goodsCateList"
          v-model="selectedGoodsCate"
          :props="goodsCateProps"
          @change="goodsCateChangeHandler"
        >
        </el-cascader>
      </el-header>
      <!-- tabs -->
      <el-tabs v-model="tabActiveName" :before-leave="tabBeforeLeaveHandler">
        <el-tab-pane label="动态参数" name="many">
          <params-list
            ref="manyParamsListRef"
            :paramsList="manyParamsList"
            :isSelectedCate="isSelectedCate"
            @addOrEditDialogHandler="addOrEditDialogHandler"
            @deleteParamsHandler="deleteParamsHandler"
            @closeVlasHanlder="closeVlasHanlder"
            @handleInputConfirm="handleInputConfirm"
          ></params-list>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <params-list
            ref="onlyParamsListRef"
            :paramsList="onlyParamsList"
            :isSelectedCate="isSelectedCate"
            @addOrEditDialogHandler="addOrEditDialogHandler"
            @deleteParamsHandler="deleteParamsHandler"
            @closeVlasHanlder="closeVlasHanlder"
            @handleInputConfirm="handleInputConfirm"
          ></params-list
        ></el-tab-pane>
      </el-tabs>
      <!-- 添加编辑参数对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="addOrEditDialogVisible"
        width="40%"
        :before-close="addOrEditDialogBeforeClose"
      >
        <el-form
          ref="addOrEditFormRef"
          :model="addOrEditForm"
          :rules="addOrEditFormRules"
          label-width="80px"
        >
          <el-form-item :label="title.slice(2)" prop="attr_name">
            <el-input v-model="addOrEditForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="addOrEditDialogBeforeClose">取 消</el-button>
          <el-button :style="btnStyle" @click="addOrEditParamsConfirmHandler">
            确 定
          </el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import paramsList from './params-list'
export default {
  name: 'params',
  data() {
    return {
      selectedGoodsCate: [], // 选中的分类
      // 级联选择器配置
      goodsCateProps: {
        label: 'cat_name',
        value: 'cat_id',
        expandTrigger: 'hover',
      },
      tabActiveName: 'many', // 激活的tabName
      isPlus: 1, // 是否添加 1添加0编辑
      addOrEditDialogVisible: false, // 控制添加或编辑参数对话框的状态
      // 添加或编辑参数表单对象
      addOrEditForm: {
        attr_name: '',
      },
      addOrEditFormRules: {
        attr_name: [
          { required: true, message: '请填写参数信息', trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    ...mapState('params', [
      'goodsCateList',
      'manyParamsList',
      'onlyParamsList',
    ]),
    // 是否选择了商品分类
    isSelectedCate() {
      return this.selectedGoodsCate.length === 3
    },
    // 添加或编辑参数对话框标题
    title() {
      let title = ''
      if (this.tabActiveName === 'many') {
        title = this.isPlus ? '添加动态参数' : '编辑动态参数'
      } else {
        title = this.isPlus ? '添加静态属性' : '编辑静态属性'
      }
      return title
    },
  },
  methods: {
    ...mapActions('params', [
      'getGoodsCateList',
      'getCateParams',
      'addOrEditParams',
      'deleteParams',
      'queryParamsVal',
    ]),
    // 选择商品分类的回调
    goodsCateChangeHandler() {
      // 选中商品三级分类
      if (this.selectedGoodsCate.length === 3) {
        this.getCateParamsHandler()
      }
    },
    // 获取分类参数
    getCateParamsHandler() {
      const params = {
        id: this.selectedGoodsCate[2],
        sel: this.tabActiveName,
      }
      this.getCateParams(params)
    },

    // 切换tab前的回调
    tabBeforeLeaveHandler(activeName) {
      if (this.selectedGoodsCate.length !== 3) {
        this.$message.info('请选中三级分类')
        return false
      }
      this.tabActiveName = activeName
      this.getCateParamsHandler()
    },
    // 添加或编辑参数对话框关闭前回调
    addOrEditDialogBeforeClose(done) {
      typeof done === 'function'
        ? done()
        : (this.addOrEditDialogVisible = false)
      this.addOrEditForm = {}
      this.$refs.addOrEditFormRef.resetFields()
    },
    // 显示添加或编辑参数对话框
    addOrEditDialogHandler(type, row) {
      type === 0 && (this.addOrEditForm = row)
      this.isPlus = type
      this.addOrEditDialogVisible = true
    },
    // 点击添加或编辑参数对话框确定按钮回调
    addOrEditParamsConfirmHandler() {
      this.$refs.addOrEditFormRef.validate(async v => {
        if (!v) return
        const requestObj = {
          id: this.selectedGoodsCate[2],
          params: {
            attr_name: this.addOrEditForm.attr_name,
            attr_sel: this.tabActiveName,
            attr_vals: '',
          },
          attrId: this.addOrEditForm.attr_id,
        }
        try {
          await this.addOrEditParams(requestObj)
          this.$message.success(this.title + '成功')
          this.getCateParamsHandler()
          this.addOrEditDialogVisible = false
        } catch (error) {}
      })
    },
    // 删除参数的回调
    async deleteParamsHandler(attrid) {
      try {
        await this.$messageBox.confirm('确定删除该参数吗？', '删除提示')
        const params = {
          id: this.selectedGoodsCate[2],
          attrid,
        }
        try {
          await this.deleteParams(params)
          this.$message.success('删除成功')
          this.getCateParamsHandler()
        } catch (error) {
          this.$message.error(error)
        }
      } catch (error) {
        this.$message.info('已取消删除')
      }
    },
    // 关闭删除参数值的回调
    closeVlasHanlder(vals, row) {
      const index = row.attr_vals.findIndex(item => item === vals)
      row.attr_vals.splice(index, 1)
      this.paramsValueHandler(row, row.attr_vals.join(','))
    },
    // 添加参数值的回调
    handleInputConfirm(value, row) {
      if (!value) return
      if (row.attr_vals.some(item => item === value)) {
        return this.$message.info('请勿添加重复的参数值')
      }
      row.attr_vals.push(value)
      this.paramsValueHandler(row, row.attr_vals.join(','))
      // 初始化子组件的数据
      this.$refs[`${this.tabActiveName}ParamsListRef`].inputValue = ''
      this.$refs[`${this.tabActiveName}ParamsListRef`].inputVisible = false
    },
    // 增删参数值
    async paramsValueHandler(row, vals) {
      const requestObj = {
        id: this.selectedGoodsCate[2],
        params: {
          attr_name: row.attr_name,
          attr_sel: this.tabActiveName,
          attr_vals: vals,
        },
        attrId: row.attr_id,
      }
      try {
        await this.addOrEditParams(requestObj)
        await this.queryParamsVal(requestObj)
        this.$message.success('更新参数值成功')
      } catch (error) {
        console.log(error)
      }
    },
  },
  components: {
    paramsList,
  },
  mounted() {
    this.getGoodsCateList()

    this.$on('addOrEditDialogHandler', this.addOrEditDialogHandler)
  },
}
</script>

<style lang="scss" scoped>
.params-container {
  .el-header {
    line-height: 60px;
    .el-cascader {
      width: 30%;
    }
  }
}
</style>
